<template>
	<view class="content">
		<view class="top">
			<customHeader></customHeader>
		</view>
		<view class="center">
			<view class="search_content">
				<view class="item_search">
					<text class="title">订单日期:</text>
					<ruiDatePicker 
						fields="day" 
						style="flex: 1;border: 1rpx solid #ccc; height: 60rpx; width: 209rpx;"
						start="2018-01-01" 
						end="2040-12-30" 
						:value="dates" 
						@change="bindChange1">
					</ruiDatePicker>
					<text>—</text>
					<ruiDatePicker 
						fields="day" 
						style="flex: 1;border: 1rpx solid #ccc; height: 60rpx; width: 209rpx;"
						start="2018-01-01" 
						end="2040-12-30" 
						:value="datee" 
						@change="bindChange2">
					</ruiDatePicker>
				</view>
				<view class="item_search" style="margin: 0 20rpx;">
					<text class="title">客户名称:</text>
					<customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc; font-size: 30rpx;"
						:options="KehuListCom"
						:value="form.kehuName"
						v-model="form.kehuName"
						@changeInput="changeInput1"
						@input="handleInput1"
					></customDownSearch>
				</view>

				<view class="item_search">
					<text class="title">单据状态:</text>
					<customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc; font-size: 30rpx;"
						:options="stateListCom"
						:value="form.dingdanStatus"
						v-model="form.dingdanStatus"
						@changeInput="changeInput2"
						@input="handleInput2"
					></customDownSearch>
				</view>
			</view>

			<view class="search_btn">
				<button @click="handleAdd">新增</button>
				<button @click="handleSearch">查询</button>
			</view>

			<!-- 表头 -->
			<view class="table_content">
				<t-table style="width: 160%;">
					<t-tr style="position: sticky; top: 0; width: 100%; background: #fff; z-index: 9; " >
						<t-th style="flex:0 0 80upx;word-break: break-all;">
							序号
						</t-th>
						<t-th>操作</t-th>
						<t-th style="flex:0 0 379upx;">单号</t-th>
						<t-th style="flex:0 0 369upx;">订单号</t-th>
						<t-th style="flex:0 0 220upx;">收款日期</t-th>
						<t-th style="flex:0 0 121upx;">状态</t-th>
						<t-th>客户名称</t-th>

						<t-th>收款类型</t-th>
						<!-- <t-th>收款方式</t-th> -->
						<t-th>收款账户</t-th>

						<t-th>实收金额</t-th>
						<t-th>优惠金额</t-th>
						<!-- <t-th>排产状态</t-th>
						<t-th>发货状态</t-th> -->

						<t-th>补差价</t-th>
						<t-th>欠款金额</t-th>
						<t-th>累计欠款</t-th>
						<t-th>客户类型</t-th>
						<t-th>制单人</t-th>
					</t-tr>
					<view style="flex: 1; overflow: auto;" v-for="(item, index) in data" :key="index">
						<t-tr>
							<t-td style="flex:0 0 80upx;word-break: break-all;">
								{{ index + 1 }}
							</t-td>
							<t-td>
								<button style="font-size: 30rpx;" @click="edit(item)" >编辑</button>
							</t-td>
							<t-td style="flex:0 0 379upx;">{{ item.no }}</t-td>
							<t-td style="flex:0 0 369upx;">
								<view style="white-space: pre-line; word-wrap: break-word;">{{ formatTotalNo(item.total_no) }}</view>
							</t-td>
							<t-td  style="flex:0 0 220upx;">{{ item.createtime }}</t-td>
							<t-td  style="flex:0 0 121upx;">
								<view style="word-wrap: break-word; width: 121upx;">{{ item.state_text}}</view>
							</t-td>
							<t-td>{{ item.company_name }}</t-td>

							<t-td>{{ item.payType_text }}</t-td>
							<!-- <t-td>{{ item.payMethod_text }}</t-td> -->
							<t-td>{{ item.acct }}</t-td>

							<t-td>{{ item.skje }}</t-td>
							<t-td>{{ item.yhje }}</t-td>
							<!-- <t-td>{{ item.state }}</t-td>
							<t-td>{{ item.state }}</t-td> -->

							<t-td>{{ item.bcj }}</t-td>
							<t-td>{{ item.qk }}</t-td>
							<t-td>{{ item.ljqk }}</t-td>
							<t-td>{{ item.custType }}</t-td>
							<t-td>{{ item.user_name }}</t-td>
						</t-tr>
					</view>

					<t-tr class="none">
						<t-th class="none" style="flex:0 0 80upx;word-break: break-all;">合计:</t-th>
						<t-th></t-th>
						<t-th class="none" style="flex:0 0 379upx;"></t-th>
						<t-th class="none" style="flex:0 0 369upx;"></t-th>
						<t-th  style="flex:0 0 220upx;" class="none"></t-th>
						<t-th style="flex:0 0 121upx;" class="none"></t-th>
						<t-th class="none"></t-th>
						<t-th class="none" style="color: red;"></t-th>
						<!-- <t-th class="none" style="color: red;"></t-th> -->
						<t-th class="none" style="color: red;"></t-th>
						<t-th class="none"></t-th>
						<t-th class="none"></t-th>
						<!-- <t-th class="none"></t-th>
						<t-th class="none"></t-th> -->
						<t-th class="none" style="color: red;">{{ bcj_com.toFixed(2) }}</t-th>
						<t-th class="none" style="color: red;">{{ qk_com.toFixed(2) }}</t-th>
						<t-th class="none" style="color: red;">{{ ljqk_com.toFixed(2) }}</t-th>
						<t-th class="none" style="color: red;"></t-th>
						<t-th class="none" style="color: red;"></t-th>
					</t-tr>
				</t-table>
			</view>

			<view class="bottom_content">
				<view>
					<myPagination 
						:key="'skd-page-' + pageIndex"
						style="height: 80rpx;"
						:totalPage="totalCount" 
						:pageIndex="pageIndex" 
						:changeCallback="parentCallback">
					</myPagination>
				</view>
			</view>
		</view>

		<!-- 新增编辑 页面 开始 -->
		<uni-popup ref="receiptPopup" type="left" :mask-click="false" :is-mask-click="false" >
			<view class="receipt_popup" >
				<view class="receipt_popup_title" :style="{ 'padding-top': statusBarHeight + 'rpx' }">客户收款单新增</view>
				<view class="receipt_form">
					<view class="dis_flex" style="padding: 15rpx 0 5rpx;">
						<view class="dis_flex"  >
							<view>单号:</view>
							<input disabled v-model="receiptForm.no" placeholder="系统自动生成"/>
						</view>

						<view class="dis_flex" style="margin: 0 20rpx;">
							<view>制单人:</view>
							<input disabled v-model="receiptForm.user_name"/>
						</view>

						<view class="dis_flex">
							<view>制单日期:</view>
							<uni-datetime-picker
								type="date"
								v-model="receiptForm.createtime"
								start="2020-3-20"
								end="2099-6-20"
								:disabled="receDisabled"
							/>
						</view>
					</view>

					<view class="dis_flex" style="padding: 15rpx 0 5rpx;">
						<view class="dis_flex" >
							<view>客户名称:</view>
							<customDownSearch
								class="search_input"
								:options="KehuListCom"
								:value="receiptForm.company_name"
								v-model="receiptForm.company_name"
								@changeInput="changeInputPopup1"
								@input="handleInputPopup1"
								:disabled="receDisabled"
							></customDownSearch>
						</view>

						<view class="dis_flex" style="margin: 0 20rpx;">
							<view>欠款:</view>
							<input disabled v-model="receiptForm.qk"/>
						</view>

						<view class="dis_flex">
							<view>累计欠款:</view>
							<input disabled v-model="receiptForm.ljqk"/>
						</view>
					</view>

					<view class="dis_flex" style="padding: 15rpx 0 5rpx;">
						<view class="dis_flex" >
							<view>收款类型:</view>
							<customDownSearch
								class="search_input"
								:options="paymentTypeList"
								:value="receiptForm.payType_text"
								v-model="receiptForm.payType_text"
								@changeInput="changeInputPopup2"
								@input="handleInputPopup2"
							></customDownSearch>
						</view>

						<!-- <view class="dis_flex" style="margin: 0 20rpx;">
							<view>收款方式:</view>
							<customDownSearch
								class="search_input"
								:options="payMethodList"
								:value="receiptForm.payMethod_text"
								v-model="receiptForm.payMethod_text"
								@changeInput="changeInputPopup3"
								@input="handleInputPopup3"
							></customDownSearch>
						</view> -->

						<view class="dis_flex" style="margin: 0 20rpx;">
							<view>收款账户:</view>
							<customDownSearch
								class="search_input"
								:options="payAccList"
								:value="receiptForm.acct"
								v-model="receiptForm.acct"
								@changeInput="changeInputPopup4"
								@input="handleInputPopup4"
							></customDownSearch>
						</view>
						<view class="dis_flex" >
							<view>收款金额:</view>
							<input type="digit" disabled v-model.number="receiptForm.skje"/>
						</view>
					</view>
					<view class="dis_flex" style="padding: 15rpx 0 5rpx;">
						<view class="dis_flex">
							<view>优惠金额:</view>
							<input type="digit" v-model.number="receiptForm.yhje"/>
						</view>

						<view class="dis_flex" style="margin: 0 20rpx;">
							<view>补差价:</view>
							<input type="digit" v-model.number="receiptForm.bcj"/>
						</view>
						<view class="dis_flex">
							<view>开票金额:</view>
							<input type="digit" v-model.number="receiptForm.kpje"/>
						</view>
					</view>
					<view class="dis_flex" style="padding: 15rpx 0 5rpx;">
						<!-- <view class="dis_flex" >
							<view>无需开票金额:</view>
							<input type="digit" v-model.number="receiptForm.bkpje"/>
						</view> -->

						<view class="dis_flex" style="margin: 0 20rpx;">
							<view>币种:</view>
							<customDownSearch
								class="search_input"
								:options="currList"
								:value="receiptForm.currency_text"
								v-model="receiptForm.currency_text"
								@changeInput="changeInputPopup5"
								@input="handleInputPopup5"
							></customDownSearch>
						</view>
					
						<view class="dis_flex">
							<view>客户类别:</view>
							<input disabled v-model="receiptForm.custType"/>
						</view>
					</view>
					<view class="dis_flex" style="padding: 15rpx 0 5rpx;">
						<view class="dis_flex">
							<view style="white-space: nowrap;">备注:</view>
							<textarea auto-height v-model="receiptForm.remark"/>
						</view>
					</view>
				</view>
				<view class="receipt_table">
					<t-table style="width: 100%;">
						<t-tr style="position: sticky; top: 0; width: 100%; background: #fff; z-index: 9; " >
							<t-th style="flex:0 0 80upx;word-break: break-all;">序号</t-th>
							<t-th style="flex:0 0 361upx;word-break: break-all;">订单号</t-th>
							<t-th>订单总数</t-th>
							<t-th>订单金额</t-th>
							<t-th>发货数量</t-th>
							<t-th>发货金额</t-th>
							<t-th>收款金额</t-th>
							<t-th  style="flex:0 0 90upx;">
								<button  @click="openDetails">
									<text class="iconfont icon-tianjia"></text>
								</button>
							</t-th>
						</t-tr>
						<view style="flex: 1; overflow: auto;" v-for="(item, index) in (receiptForm.receiptOrders || [])" :key="index">
							<t-tr>
								<t-th style="flex:0 0 80upx;word-break: break-all;">{{index+1}}</t-th>
								<t-th style="flex:0 0 361upx;word-break: break-all;">{{item.no}}</t-th>
								<t-th>{{item.total}}</t-th>
								<t-th>{{item.amount}}</t-th>
								<t-th>{{item.disp_qty}}</t-th>
								<t-th>{{item.disp_amount}}</t-th>
								<t-th>
									<input type="digit" v-model="item.recd_amount" @input="changeRecdAmount" />
								</t-th>
								<t-th  style="flex:0 0 90upx;">
									<button @click="delOrder(item, index)">
										<text class="iconfont icon-x1"></text>
									</button>
								</t-th>
							</t-tr>
						</view>
						<t-tr>
							<t-th style="flex:0 0 80upx;word-break: break-all;">合计</t-th>
							<t-th style="flex:0 0 361upx;word-break: break-all;"></t-th>
							<t-th>{{ receipt_map_com.total().toFixed(0) || 0 }}</t-th>
							<t-th>{{ receipt_map_com.amount().toFixed(2) || 0 }}</t-th>
							<t-th>{{ receipt_map_com.disp_qty().toFixed(0) || 0 }}</t-th>
							<t-th>{{ receipt_map_com.disp_amount().toFixed(2) || 0 }}</t-th>
							<t-th>{{ receipt_map_com.recd_amount().toFixed(2) || 0 }}</t-th>
							<t-th  style="flex:0 0 90upx;"></t-th>
						</t-tr>
					</t-table>
				</view>
				<view class="footer_btn">
					<button @click="handleReceClose" size="mini">关闭</button>
					<button :disabled="saveDisable" @click="handleReceSure" hover-class="btn_hover" size="mini">确认</button>
				</view>
			</view>
		</uni-popup>
		<!-- 新增编辑 页面 结束 -->

		<!-- 订单明细 页面 开始 -->
		<uni-popup ref="orderDePopup" type="center" :mask-click="false" :is-mask-click="false" >
			<view class="order_dePopup">
				<view class="order_popup_title">选择订单号</view>
				<view class="order_table" >
					<t-table style="width: 100%;">
						<t-tr style="position: sticky; top: 0; width: 100%; background: #fff; z-index: 9; " >
							<t-th style="flex:0 0 80upx;word-break: break-all;">
								<checkbox-group @change="changeAll">
									<checkbox value="selectAll" :checked="selectAll" />
								</checkbox-group>
							</t-th>
							<t-th style="flex:0 0 479upx;">订单号</t-th>
							<t-th style="flex:0 0 343upx;">日期</t-th>
							<t-th>客户</t-th>
							<!-- <t-th style="flex:0 0 223upx;">状态</t-th> -->
						</t-tr>
						<t-tr v-for="(item, index) in orderDetailsList" :key="index" >
							<t-th style="flex:0 0 80upx;word-break: break-all;">
								<checkbox-group @click="changeBox(item)">
									<checkbox value="selectAll" :checked="item.checked" />
								</checkbox-group>
							</t-th>
							<t-th style="flex:0 0 479upx;">{{item.no}}</t-th>
							<t-th style="flex:0 0 343upx;">{{item.createtime}}</t-th>
							<t-th>{{item.customer_name}}</t-th>
							<!-- <t-th style="flex:0 0 223upx;">状态</t-th> -->
						</t-tr>
					</t-table>
				</view>
				<view style="margin: 20rpx 0;">
					<myPagination 
						:key="'skd-order-' + page_order_Index"
						style="height: 80rpx;"
						:totalPage="total_order_Count" 
						:pageIndex="page_order_Index" 
						:changeCallback="orderCallback">
					</myPagination>
				</view>
				<view class="footer_btn">
					<button @click="handleOrderClose" size="mini">关闭</button>
					<button @click="handleOrderSure" hover-class="btn_hover" size="mini">确认</button>
				</view>
			</view>
		</uni-popup>
		<!-- 订单明细 页面 结束 -->

	</view>
</template>

<script>
import customHeader from '@/components/custom-header/custom-header.vue'
import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue'
import customDownSearch from '@/components/custom-downSearch/custom-downSearch.vue'
import customPagination from '@/components/custom-pagination/custom-pagination.vue'
import myPagination from '@/components/my-pagination/my-pagination.vue'
import tTable from '@/components/t-table/t-table.vue'
import tTh from '@/components/t-table/t-th.vue'
import tTr from '@/components/t-table/t-tr.vue'
import tTd from '@/components/t-table/t-td.vue'

import { tableDetail, dingdState, dingdOrder, deleteDd, getReceiptDetail, query_accts, detail_receipts, save_receipts, get_receipt_amount } from "@/api/modules/table.js"
import { getKehuList, getKdPersonList, getGradeList, getAreaList } from '@/api/modules/select.js'
const { currentdate, beforedate } = getNowFormatDate()
	var timer_s = beforedate
	var timer_e = currentdate
	function getNowFormatDate() {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var month = date.getMonth() + 1;  // 当前月
		var month2 = month - 2;  // 当前月往前推2个月
		var strDate = date.getDate();  // 当前日
		
		// 如果月份小于10，前面加0
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		
		// 如果月份2小于10，前面加0
		if (month2 < 1) {
			month2 += 12;  // 如果月份为负数，回到上一年
			date.setFullYear(date.getFullYear() - 1);  // 年份减1
		}
		if (month2 >= 1 && month2 <= 9) {
			month2 = "0" + month2;
		}

		// 如果日期小于10，前面加0
		if (strDate >= 1 && strDate <= 9) {
			strDate = "0" + strDate;
		}

		var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
		var beforedate = date.getFullYear() + seperator1 + month2 + seperator1 + strDate;
		return {
			currentdate,
			beforedate
		};
	}

	function debounce  (func, wait) {  
		let timeout;  
		return function() {  
			const context = this;  
			const args = arguments;  
			if (timeout) clearTimeout(timeout);  
			timeout = setTimeout(function() {  
			func.apply(context, args);  
			}, wait);  
		};  
	}

	export default {
		components:{
			customHeader, 
			ruiDatePicker,
			customDownSearch,
			customPagination,
			myPagination,
			tTable,
		    tTh,
		    tTr,
		    tTd,
		},
		data() {
			return {
				dates: timer_s,
				datee: timer_e,
				form: {
					kehuName: '', // 客户名称
					dingdanStatus: '编辑', // 订单状态
					yewuyuan: '', // 业务员
					danhao: '', // 订单号
				},
				selectAll: false, // 全选按钮
				data: [],

				kehuList: [], // 客户名称
				dingdStateList: [
					{ text: '编辑', no: '1' },
					{ text: '审核', no: '2' },
					{ text: '作废', no: '3' },
				], // 订单状态
				orderList: [], // 订单号
				timingNum: 1, // 判断 要不要跳转
				pageSize: 10, // 下单页数
				pageIndex: 1, // 当前页数
				totalCount: 0, // 应该有多少条数据
				scrollTop: 0,
				statusBarHeight: 0, // 状态栏高度
				receiptForm: {
					receiptOrders: []
				}, // 收款单表单
				newPaymentTypeList: [], // 收款类型
				paymentTypeList: [], // 收款类型
				payMethodList: [], // 收款方式
				newPayMethodList: [], // 收款方式
				payAccList: [], // 收款账户
				newPayAccList: [], // 收款账户
				currList: [], // 必种
				newCurrList: [], // 必种
				receDisabled: false, // 回显时制单时间和客户不能修改
				orderDetailsList: [], // 订单明细
				total_order_Count: 0, // 订单明细总数
				page_order_Index: 1, // 订单明细当前页数
				page_order_Size: 20, // 每次请求20条
				saveDisable: false, // 保存按钮禁用

				debouncedGetKehu: debounce(this.getKehu, 500),  // 客户名称 防抖
				// debouncedState: debounce(this._dingdState, 500),  // 状态 防抖
				debouncedPay: debounce(this._getPay, 500),  // 收款类型 防抖
				debouncedPayAcc: debounce(this._payAccount, 500),  // 收款类型 防抖
				active_menu_id: '', // 当前选中的菜单
			}
		},
		onLoad(r) {
			this.active_menu_id = r.id
			this.getKehu(); // 客户名称
			this._dingdState(); // 获取订单状态
			this._getPay(); // 收款类型

			this._payMethod(); // 收款方式
			this._payAccount(); // 收款账户
			this._currency(); // 币种
		},
		
		computed: {
			KehuListCom(){
				let arr = [];
				 (this.kehuList || []).forEach(i => {
					arr.push(i.name)
				 })
				 return arr
			},
			stateListCom(){
				let arr = [];
				 (this.dingdStateList || []).forEach(i => {
					arr.push(i.text)
				 })
				 return arr
			},
			bcj_com() {
				return (this.data || []).reduce((a, b) => a + (Number(b.bcj) || 0), 0)
			},
			qk_com() {
				return (this.data || []).reduce((a, b) => a + (Number(b.qk) || 0), 0)
			},
			ljqk_com() {
				return (this.data || []).reduce((a, b) => a + (Number(b.ljqk) || 0), 0)
			},
			receipt_map_com() {
				return {
					'total' : () => (this.receiptForm.receiptOrders || []).reduce((a, b) => a + (Number(b.total) || 0), 0),
					'amount' : () => (this.receiptForm.receiptOrders || []).reduce((a, b) => a + (Number(b.amount) || 0), 0),
					'disp_qty' : () => (this.receiptForm.receiptOrders || []).reduce((a, b) => a + (Number(b.disp_qty) || 0), 0),
					'disp_amount' : () => (this.receiptForm.receiptOrders || []).reduce((a, b) => a + (Number(b.disp_amount) || 0), 0),
					'recd_amount' : () => (this.receiptForm.receiptOrders || []).reduce((a, b) => a + (Number(b.recd_amount) || 0), 0),
				}
			}
		},
		methods: {
			handleOrderSure() {
				let selectList = this.orderDetailsList.filter(i => i.checked).map(i => ({...i, recd_amount: i.recd_amount || 0}))

				if (!selectList.length) {
					uni.showToast({
						title: '请选择订单',
						icon: 'none',
						duration: 2000
					})
					return
				}

				if (!this.receiptForm.receiptOrders) {
					this.receiptForm.receiptOrders = [];
				}

				let arr = []
				selectList.forEach(i => {
				    if (!this.receiptForm.receiptOrders.filter(j => i.no == j.no).length) {
						arr.push(i)
					}
				})
				this.receiptForm = {
					...this.receiptForm,
					receiptOrders: [...this.receiptForm.receiptOrders, ...arr]
				}
				this.receiptForm.skje = this.receipt_map_com.recd_amount()
				this.handleOrderClose()

			},
			handleOrderClose() {
				this.$refs.orderDePopup.close()
				this.selectAll = false
			},
			changeAll() { // 全选
				this.selectAll = !this.selectAll
				if (this.selectAll) {
					this.orderDetailsList = this.orderDetailsList.map((i, j) => ({...i, checked: true}))
				} else if (!this.selectAll) {
					this.orderDetailsList = this.orderDetailsList.map((i, j) => ({...i, checked: false}))
				}
			},
			changeBox(item) { // 单选
				item.checked = !item.checked
			},
			async openDetails() {
				let company_id = this.kehuList.find(i => i.name == this.receiptForm.company_name)?.id || ''
				if (!company_id) {
					uni.showToast({
						title: '请先选择客户名称',
						icon: 'none',
						duration: 2000
					})
					return
				}
				let param = {
					orbys: [{code: "materiel_name", by: "asc"}],
					paging: {
						pageIndex: 1,
						pageSize: this.page_order_Size,
					},
					query: {
						customer_id: company_id,
						state: 'wmssoy_03',
						except: (this.receiptForm.receiptOrders || []).map(i => ({no: i.no}))
					}
				}
				this.getDetailsData(param)
			},
			// 删除订单
			delOrder(item, index) {
				this.receiptForm = {
					...this.receiptForm,
					receiptOrders: (this.receiptForm.receiptOrders || []).filter(i => i.no != item.no)
				}
				this.receiptForm.skje = this.receipt_map_com.recd_amount()
			},
			// 修改收款单 汇总
			changeRecdAmount() {
				this.receiptForm = {
					...this.receiptForm,
					skje: this.receipt_map_com.recd_amount()
				}
			},
			async orderCallback(pages) {
				let company_id = this.kehuList.find(i => i.name == this.receiptForm.company_name)?.id || ''
				let param = {
					orbys: [{code: "materiel_name", by: "asc"}],
					paging: {
						pageIndex: pages,
						pageSize: this.page_order_Size,
					},
					query: {
						customer_id: company_id,
						state: 'wmssoy_03',
						except: (this.receiptForm.receiptOrders || []).map(i => ({no: i.no}))
					}
				}
				this.getDetailsData(param)
			},
			async getDetailsData(param) {
				this.orderDetailsList = []
				const res = await tableDetail(JSON.stringify(param))
				const { data: { data, status, message } } = res || {}
				if (status == 'success') {
					if (!data.sorders.length) {
						uni.showToast({
							title: '暂无数据!',
							duration: 2000,
							icon: 'none'
						});
						return;
					}
					this.orderDetailsList = data.sorders.map(i => ({
						...i,
						checked: false,
					}))
					this.total_order_Count = Math.ceil(data.paging.total / this.page_order_Size)
					console.log('== pages ', this.total_order_Count)
					this.$refs.orderDePopup.open('center')
					
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				} 

			},
			parentCallback(pages) {
				this.pageIndex = pages
				this.scrollTop = 0
				let param = {
					paging: {
						pageIndex: pages,
						pageSize: this.pageSize,
					}, 
					query: {
						state: this.dingdStateList.filter(i => i.text == this.form.dingdanStatus)[0]?.no || '', // 订单状态
						company_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id || '', // 客户订单
						start_date: this.dates, 
						end_date: this.datee,
						active_menu_id: this.active_menu_id, // 菜单id
						// search: this.form.danhao, //查询指定产品订单
					}
				}
				this._tableDetail(param);
			},
			handleSearch() {
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: this.pageSize,
					}, 
					query: {
						state: this.dingdStateList.filter(i => i.text == this.form.dingdanStatus)[0]?.no || '', // 订单状态
						company_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id || '', // 客户订单
						start_date: this.dates, 
						end_date: this.datee,
						// search: this.form.danhao, //查询指定产品订单
						active_menu_id: this.active_menu_id, // 菜单id
					}
				}

				this.pageIndex = 1
				this._tableDetail(param);
			},
			async edit(item) {
				this.receiptForm = {}
				this.saveDisable = false
				const systemInfo = uni.getSystemInfoSync();
				this.statusBarHeight = systemInfo.statusBarHeight * 2;
				const res = await detail_receipts(JSON.stringify({ id: item.id }))
				console.log('== res ', res)
				const { data: { data, status, message } } = res || {}
				if (status == 'success') {
					this.receiptForm = data
					this.$refs.receiptPopup.open('left')
					this.receDisabled = true
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				}

			},
			async handleAdd() {
				this.saveDisable = false
				const systemInfo = uni.getSystemInfoSync();
				this.statusBarHeight = systemInfo.statusBarHeight * 2;
				this.receiptForm = {}
				let { name, id } = uni.getStorageSync('userInfo').length ? JSON.parse(uni.getStorageSync('userInfo')) : {}
				const date = new Date();
				const year = date.getFullYear();
				let month = date.getMonth() + 1; // 月份是从0开始的，所以需要加1
				let day = date.getDate();
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				const formattedDate = `${year}-${month}-${day}`;

				this.receiptForm = {
					user_name: name,
					user_id: id,
					createtime: formattedDate,
					no: '',
					qk: '',
					ljqk: '',
					skje: '',
					yhje: '',
					bcj: '',
					kpje: '',
					bkpje: '',
					custType: '',
					remark: '',
					currency_text: '人民币',
					receiptOrders: []
				}

				this.$refs.receiptPopup.open('left')
			},
			async handleReceSure() {

				if (!this.receiptForm.company_name) {
					uni.showToast({
						title: '请选择客户名称!',
						duration: 2000,
						icon: 'none'
					});
					return
				}

				if (!this.receiptForm.createtime) {
					uni.showToast({
						title: '请选择制单日期!',
						duration: 2000,
						icon: 'none'
					});
					return
				}

				if (!this.receiptForm.skje) {
					uni.showToast({
						title: '请输入收款金额!',
						duration: 2000,
						icon: 'none'
					});
					return
				}

				this.receiptForm = {
					...this.receiptForm,
					company_id: this.kehuList.find(i => i.name == this.receiptForm.company_name)?.id || '',

					payType_id: this.newPaymentTypeList.find(i => i.text == this.receiptForm.payType_text)?.id || '',

					payMethod_id: this.newPayMethodList.find(i => i.text == this.receiptForm.payMethod_text)?.id || '',

					currency_id: this.newCurrList.find(i => i.text == this.receiptForm.currency_text)?.id || '',
				}
				console.log('== 11 ', this.receiptForm )
				
				this.saveDisable = true
				const res = await save_receipts(JSON.stringify(this.receiptForm))
				const { data: { data, status, message } } = res || {}
				if (status == 'success') {
					uni.showToast({
						title: '成功!',
						duration: 2000,
						icon: 'none'
					});
					this.handleReceClose()

					let param = {
						paging: {
							pageIndex: this.pageIndex,
							pageSize: this.pageSize,
						}, 
						query: {
							state: this.dingdStateList.filter(i => i.text == this.form.dingdanStatus)[0]?.no || '', // 订单状态
							company_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id || '', // 客户订单
							start_date: this.dates, 
							end_date: this.datee,
							// search: this.form.danhao, //查询指定产品订单
							active_menu_id: this.active_menu_id, // 菜单id
						}
					}
					this._tableDetail(param);

				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
					this.saveDisable = false
				}
			},
			handleReceClose() { // 关闭弹出框
				this.receiptForm = {}
				this.$refs.receiptPopup.close()
				this.receDisabled = false
			},
			
			changeInput1(opt) {
				this.form.kehuName = opt
			},
			handleInput1(opt) {
				this.form.kehuName = opt
				this.debouncedGetKehu(opt)
			},
			changeInputPopup1(opt) {
				this.receiptForm.company_name = opt
				this.getReceAmount()
			},
			async getReceAmount() {
				let item = this.kehuList.find(i => i.name == this.receiptForm.company_name)
				let param = {
					company_id: item?.id || '',
					createtime: this.receiptForm.createtime
				}
				const res = await get_receipt_amount(JSON.stringify(param))
				const { data: { data, status, message } } = res || {}
				if (status == 'success') {
					this.receiptForm = {
						...this.receiptForm,
						qk: data.qk,
						ljqk: data.ljqk,
						custType: item?.cate_name || ''
					}

				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				}
			},
			handleInputPopup1(opt) {
				this.receiptForm.company_name = opt
				if (opt === '') {
					this.receiptForm = {
						...this.receiptForm,
						qk: '',
						ljqk: '',
						custType: '',
					}
				}
				this.debouncedGetKehu(opt)
			},
			changeInputPopup2(opt) {
				this.receiptForm.payType_text = opt
			},
			handleInputPopup2(opt) {
				this.receiptForm.payType_text = opt
				this.debouncedPay(opt)
			},
			changeInputPopup3(opt) {
				this.receiptForm.payMethod_text = opt
			},
			handleInputPopup3(opt) {
				this.receiptForm.payMethod_text = opt
			},
			changeInputPopup4(opt) {
				this.receiptForm.acct = opt
			},
			handleInputPopup4(opt) {
				this.receiptForm.acct = opt
				this.debouncedPayAcc(opt)
			},
			changeInputPopup5(opt) {
				this.receiptForm.currency_text = opt
			},
			handleInputPopup5(opt) {
				this.receiptForm.currency_text = opt
			},

			changeInput2(opt) {
				this.form.dingdanStatus = opt
			},
			handleInput2(opt) {
				this.form.dingdanStatus = opt
				// this.debouncedState(opt)
			},
			

			bindChange1(value) { // 日期选择
				this.dates = value;
			},
			bindChange2(value) { // 日期选择
				this.datee = value;
			},
			formatTotalNo(totalNo) {
				// 将逗号分隔的字符串转换为换行显示
				if (!totalNo) return '';
				return totalNo.replace(/,/g, '\n');
			},
			async _tableDetail(param) {
				const res = await getReceiptDetail(JSON.stringify(param))
				const { data: { data, status, message } } = res || {}
				if (status == 'success') {
					if (!data.receipts.length) {
						uni.showToast({
							title: '暂无数据!',
							duration: 2000,
							icon: 'none'
						});
					}
					this.totalCount = Math.ceil(data.paging.total / this.pageSize)
					this.data = (data.receipts || []).map(i => ({ 
						...i, 
						check: false, 
					}))
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				} 
			},
			async getKehu(str='') { // 客户信息
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						type_nos: ["customer"],
						valid: true,
						search: str, // 搜索字段
					},
				}
				const res = await getKehuList(JSON.stringify(param))
				const { data: { data } } = res || {}
				// console.log('== 客户信息', res)
				this.kehuList = (data.companys ? data.companys : [])
			},

			async _dingdState(str = '') { // 订单状态
				// let param = {
				// 	paging: {
				// 		pageIndex: 1,
				// 		pageSize: 200,
				// 	},
				// 	query: {
				// 		dictype_no: "salesReceiptState",
				// 		search: str, // 搜索字段
				// 		// valid: 'true',
				// 	},
				// }
				// const res = await dingdState(JSON.stringify(param)) 
				// const { data:{ data } } = res || {}
				// this.dingdStateList = (data.dictionaries ? data.dictionaries : [])
				
				let param1 = {
				paging: {
						pageIndex: 1,
						pageSize: this.pageSize,
					}, 
					query: {
						state: this.dingdStateList.filter(i => i.text == this.form.dingdanStatus)[0]?.no || '', // 订单状态
						// company_name: '', // 客户订单
						start_date: this.dates, 
						end_date: this.datee,
						active_menu_id: this.active_menu_id, // 菜单id
					}
				}
				this._tableDetail(param1);
				
			},
			async _payMethod(str = '') { // 收款方式
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						dictype_no: "paymentMethod",
						search: str,
					},
				}
				const res = await dingdState(JSON.stringify(param)) 
				const { data:{ data } } = res || {}
				this.newPayMethodList = (data.dictionaries || [])
				this.payMethodList = this.newPayMethodList.map(i => i.text)
			},
			async _currency(str = '') { // 币种
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 2000,
					},
					query: {
						dictype_no: "currency",
						search: str,
					},
				}
				const res = await dingdState(JSON.stringify(param)) 
				const { data:{ data } } = res || {}
				this.newCurrList = (data.dictionaries || [])
				this.currList = this.newCurrList.map(i => i.text)
			},
			async _payAccount(str = '') { // 收款账户
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						search: str, // 搜索字段
						valid: 'true',
					},
				}
				const res = await query_accts(JSON.stringify(param)) 
				const { data:{ data } } = res || {}
				this.newPayAccList = (data.accounts || [])
				this.payAccList = this.newPayAccList.map(i => i.name)
			},
			async _getPay(str = '') { // 收款类型
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						dictype_no: "paymentType",
						search: str, // 搜索字段
					},
				}
				const res = await dingdState(JSON.stringify(param))

				console.log('收款类型', res)
				const { data: { data } } = res || {}
				this.newPaymentTypeList = (data.dictionaries || [])
				this.paymentTypeList = this.newPaymentTypeList.map(i => i.text)
			},
			
		}
	}
</script>

<style lang="less" scoped>
.content {
	height: 100vh;
	display: flex;
	flex-direction: column;
	.top {
		position: fixed;
		width: 100%;
		z-index: 12;
	}

	.center {
		padding: 0 40rpx;
		padding-top: 158rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: auto;

		/* 隐藏滚动条 
		::-webkit-scrollbar {
			display: none;
		}
		-ms-overflow-style: none;
		scrollbar-width: none;
		*/

		.search_content {
			display: flex;
			align-items: center;
			// justify-content: space-between;
			margin-top: 30rpx;
			width: 100%;
			.item_search {
				display: flex;
				align-items: center;
				height: 60rpx;
				width: 33%;

				.title {
					font-size: 40rpx;
					font-weight: 700;
					width: 200rpx;
				}
			}
		}

		.search_btn {
			display: flex;
			justify-content: space-between;
			margin: 30rpx;

			button {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 80rpx;
				width: 360rpx;
				color: #fff;
				margin: 0;
				font-size: 50rpx;
			}

			button:nth-child(1) {
				background: #2e95db;
			}
			button:nth-child(2) {
				background: #f59a23;
			}
		}
		
		.table_content {
			flex: 1;
			width: 100%;
			overflow: auto;
		}

		.bottom_content {
			margin: 20rpx 0;
			font-size: 34rpx;

			.none {
				border: none;
			}
		}
	}

	.receipt_popup {
		width: 100vh;
		height: 100vh;
		background: #fff;
		padding: 0rpx 20rpx 20rpx;
		font-size: 30rpx;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;

		.receipt_popup_title {
			font-size: 40rpx;
			font-weight: 700;
			border-bottom: 1rpx solid #ccc;
			padding-bottom: 20rpx;
		}

		.receipt_form {
			.dis_flex {
				display: flex;
				align-items: center;
				width: 100%;

				input, textarea {
					flex: 1;
					border: 1rpx solid #f0f0f0;
					padding: 5rpx 15rpx;
					border-radius: 10rpx;
				}

				.search_input {
					flex: 1;
					border: 1rpx solid #f0f0f0;
					border-radius: 10rpx;
				}
			}
		}

		.receipt_table {
			flex: 1;
			overflow: auto;
			.icon-tianjia {
				color: #1dc0e3;
			}
			.icon-x1 {
				color: #d81e06;
			}
			button {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 60rpx;
			}
		}

		.footer_btn {
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding-top: 20rpx;
			border-top: 1rpx solid #ccc;
			button {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0;
			}

			button:nth-child(2) {
				background: #2e95db;
				color: #fff;
			}
			.btn_hover {
				background: #2878ae !important;
			}
		}
	}

	// 订单明细弹出框
	.order_dePopup {
		width: 80vw;
		height: 80vh;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		.order_popup_title {
			font-size: 40rpx;
			font-weight: 700;
			border-bottom: 1rpx solid #ccc;
			padding-bottom: 20rpx;
		}

		.order_table {
			flex: 1;
			overflow: auto;
		}


		.footer_btn {
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding-top: 20rpx;
			border-top: 1rpx solid #ccc;
			button {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0;
			}
			button:nth-child(2) {
				background: #2e95db;
				color: #fff;
			}
			.btn_hover {
				background: #2878ae !important;
			}
		}
	}
}
</style>
